package it.tukano.swingdeco.containers;

import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.WindowConstants;

/**
 * JFrame extension
 * @author pgi
 */
public class JFrameExt extends JFrame {

    private static final long serialVersionUID = 0;

    /**
     * Instance initializer
     */
    public JFrameExt() {
    }

    /**
     * Instance initializer
     * @param title the title of the frame
     */
    public JFrameExt(String title) {
        super(title);
    }

    public JFrameExt withIcon(ImageIcon icon) {
        setIconImage(icon.getImage());
        return this;
    }

    /**
     * Add a component and return this
     * @param c the component to add
     * @param constraints the layout constraints to use
     * @return this
     */
    public JFrameExt append(Component c, Object constraints) {
        add(c, constraints);
        return this;
    }
    
    public JFrameExt defaultDispose() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        return this;
    }

    public JFrameExt displayOnScreen() {
        setVisible(true);
        return this;
    }

    /**
     * Add a menu bar and return this
     * @param menuBar the menu bar to add
     * @return this
     */
    public JFrameExt withMenuBar(JMenuBar menuBar) {
        setJMenuBar(menuBar);
        return this;
    }

    /**
     * Do something on close
     * @param task the task to execute when the window closes
     * @return this
     */
    public JFrameExt onClosing(final Runnable task) {
        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                task.run();
            }
        });
        return this;
    }
    
    public JFrameExt onClosed(final Runnable task) {
        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {
                task.run();
            }
        });
        return this;
    }

    public JFrameExt withWindowListener(WindowListener listener) {
        addWindowListener(listener);
        return this;
    }

    /**
     * Set the size and return this
     * @param width the new width of the window
     * @param height the new height of the window
     * @return this
     */
    public JFrameExt withSize(int width, int height) {
        setSize(width, height);
        return this;
    }
    
    public JFrameExt packAndShow() {
        pack();
        setVisible(true);
        return this;
    }

    public JFrameExt doNothingOnClose() {
        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        return this;
    }
}
